const Sudoku = require('../../utils/sudoku.js')
const network = require('../../utils/network')

Page({
  data: {
    user: null,
    rules: [],
    grids: [],
    answerFlag: false,
    hasChecked: false,
    currentIndex: -1,
    checkAnswer: false,
    currentDim: 3 // 当前维度
  },
  onLoad() {
    wx.setNavigationBarTitle({
      title: '开始游戏'
    })

    this.fetchPoint()
    this.reset()
  },

  onShareAppMessage(res) {
    return {
      title: '聪明格子',
      path: '/pages/login/login',
      imageUrl: './sudokuShare.jpg'
    }
  },

  /**
   * @desc 重玩
   * @param dim
   */
  reset(dim) {
    dim = dim || this.data.currentDim

    return this.fetchUser()
      .then(_ => {
        return this.genSudoku(dim)
      })
      .then(data => {
        return this.parseData(data, dim)
      })
      .then(grids => {
        this.setData({
          currentDim: dim,
          grids,
          answerFlag: false,
          hasChecked: false,
          checkAnswer: false,
          currentIndex: -1
        })
      })
  },

  /**
   * @desc 获取用户信息
   */
  fetchUser() {
    return network
      .post('game/getUserLevel')
      .then(data => {
        this.setData({
          user: data
        })
      })
      .catch(err => {
        console.log(err)
      })
  },

  /**
   * @desc 获取积分信息
   */
  fetchPoint() {
    return network
      .post('game/getGameRule')
      .then(data => {
        this.setData({
          rules: data
        })
      })
      .catch(err => {
        console.log(err)
      })
  },

  /**
   * @desc 加分
   */
  addPoint() {
    let ruleId = this.data.rules.filter(r => {
      return r.level_name == `${this.data.currentDim}*${this.data.currentDim}`
    })[0].id

    if (this.data.user) {
      return network
        .post('game/addPoint', {
          ruleId
        })
        .catch(err => console.log(err))
    } else {
      return Promise.resolve()
    }
  },

  /**
   * @desc 生成 sudoku
   * @param dim
   */
  genSudoku(dim) {
    return Promise.resolve(Sudoku.addNewQuestion(dim))
  },

  /**
   * @desc 解析数据
   * @param {*} data sudoku 数据
   * @param dim
   */
  parseData(data, dim) {
    // console.log(data)
    let parsedFigure = this.parseFigure(data.figure)

    let answerList = data.answer.split('|')
    let cageList = data.cage.split('|')

    let grids = new Array(dim * dim).fill(0).map((_, i) => {
      return {
        answer: +answerList[i],
        cage: +cageList[i]
      }
    })

    parsedFigure.forEach(f => {
      let i = +f.pos[0] * dim + +f.pos[1]

      grids[i].number = +f.number
      grids[i].symbol = f.symbol
    })

    grids = this.clearBorder(grids, dim)

    // console.log(grids)
    return grids
  },

  /**
   * @desc 解析 figure
   * @param {*} figure
   */
  parseFigure(figure) {
    let splitedData = figure.split('$').map(f => {
      let t = f.split('|')
      return {
        number: t[0],
        symbol: t[1],
        pos: t[2].split('-')
      }
    })
    return splitedData
  },

  /**
   * @desc 消除边界
   * @param {*} grids
   * @param dim
   */
  clearBorder(grids, dim) {
    grids.forEach((g, i) => {
      if (i < grids.length - 1) {
        // 遍历到倒数第二个
        let nextSameCageIndex = grids.slice(i + 1).findIndex((c, j) => {
          return c.cage === g.cage
        })
        nextSameCageIndex += i + 1

        if (nextSameCageIndex == i + 1) {
          // 在右边, 去除左边线
          grids[i].right = true
          grids[nextSameCageIndex].left = true
        } else if (nextSameCageIndex == i + dim) {
          // 在下边, 去除上边线
          grids[i].bottom = true
          grids[nextSameCageIndex].top = true
        }
      }
    })
    return grids
  },

  /**
   * @desc 选择数字
   * @param {*} e
   */
  showSel(e) {
    if (this.data.answerFlag || this.data.hasChecked) {
      // 查看答案下不能选择
      return
    }
    let index = e.currentTarget.dataset.index
    let itemList = new Array(this.data.currentDim)
      .fill(0)
      .map((v, i) => i + 1 + '') // 字符串

    this.setData({
      currentIndex: index
    })

    wx.showActionSheet({
      itemList,
      success: res => {
        this.setAnswer(+index, +itemList[res.tapIndex])
      }
    })
  },

  /**
   * @desc 设置答案
   * @param {*} index
   * @param {*} value
   */
  setAnswer(index, value) {
    let grids = this.data.grids.map((g, i) => {
      if (i === index) {
        g.userAnswer = value
      }
      return g
    })

    this.setData({
      grids
    })

    this.checkAnswer()
  },

  /**
   * @desc 清除当前选择框
   * @param e
   */
  clearSel(e){
    let index = e.currentTarget.dataset.index
    let grids = this.data.grids.map((g, i) => {
      if (i === index) {
        g.userAnswer = ''
      }
      return g
    })

    this.setData({
      grids
    })
  },

  /**
   * @desc （不）清除答案
   */
  clearAnswer() {
    this.setData({
      hasChecked: false,
      checkAnswer: false,
      answerFlag: false
    })
  },

  /**
   * @desc 检查答案
   */
  checkAnswer() {
    if (this.data.hasChecked) {
      // 查看答案下不能做题
      return
    }
    // 完整性检查
    for (let g of this.data.grids) {
      if (!g.userAnswer) {
        return false
      }
    }

    let hasWrong = !(
      Sudoku.checkRowCol(this.data.grids) && Sudoku.checkCage(this.data.grids)
    )

    if (hasWrong) {
      let tempGrids = Object.assign([], this.data.grids)
      for (let i = 0; i < tempGrids.length; ++i) {
        let g = tempGrids[i]
        if (g.userAnswer !== g.answer) {
          g.wrong = true
          hasWrong = true
        }
      }
      this.setData({
        grids: tempGrids,
        hasChecked: true
      })

      wx.showModal({
        title: '很遗憾',
        content: '您本次挑战失败',
        confirmText: '重新挑战',
        cancelText: '查看答案',
        success: res => {
          if (res.confirm) {
            this.clearAnswer()
          } else if (res.cancel) {
            this.showAnswer()
          }
        }
      })
      return false
    }

    return this.addPoint().then(_ => {
      wx.showModal({
        title: '恭喜您',
        content: '通关成功，挑战一下更高难度吧！',
        showCancel: false,
        confirmText: '确定',
        success: res => {
          this.reset()
        }
      })
    })
  },

  /**
   * @desc 显示答案
   */
  showAnswer() {
    this.setData({
      checkAnswer: true,
      answerFlag: true,
      currentIndex: -1
    })
  },

  /**
   * @desc 关闭答案
   */
  hideAnswer() {
    this.setData({
      answerFlag: false,
      currentIndex: -1
    })
  },

  /**
   * @desc 设置维度
   * @param {*} e
   */
  setDim(e) {
    let dim = +e.currentTarget.dataset.dim
    this.reset(dim)
  },

  /**
   * @desc 一键做题
   */
  solve() {
    if (this.data.hasChecked) {
      // 查看答案下不能做题
      return
    }
    this.setData({
      currentIndex: -1,
      grids: this.data.grids.map(g => {
        g.userAnswer = g.answer
        return g
      })
    })
  },

  /**
   * @desc 去规则页
   */
  toRule() {
    wx.navigateTo({
      url: '/pages/rule/rule'
    })
  },

  /**
   * @desc 重新登录
   */
  relogin() {
    wx.reLaunch({
      url: '/pages/login/login'
    })
  }
})
